package com.ahdy.controller;

import com.ahdy.entity.LocationSharing;
import com.ahdy.entity.ShareTarget;
import com.ahdy.service.LocationSharingService;
import com.ahdy.service.ShareTargetService;
import com.ahdy.tool.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 位置共享控制器
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class LocationSharingController {
    
    @Autowired
    private LocationSharingService locationSharingService;
    
    @Autowired
    private ShareTargetService shareTargetService;
    
    /**
     * 保存位置共享信息
     * @param locationSharing 位置共享信息
     * @return 操作结果
     */
    @PostMapping("/location-sharing")
    public R<String> saveLocationSharing(@RequestBody LocationSharing locationSharing) {
        log.info("保存位置共享信息: {}", locationSharing);
        try {
            // 如果未提供时间戳，则使用当前时间
            if (locationSharing.getLocationTimestamp() == null) {
                locationSharing.setLocationTimestamp(System.currentTimeMillis());
            }
            
            boolean result = locationSharingService.saveLocationSharing(locationSharing);
            if (result) {
                return R.success("位置共享成功");
            } else {
                return R.error("位置共享失败");
            }
        } catch (Exception e) {
            log.error("位置共享异常", e);
            return R.error("位置共享异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户最新位置
     * @param userId 用户ID
     * @return 最新位置信息
     */
    @GetMapping("/location-sharing/latest/{userId}")
    public R<LocationSharing> getLatestLocationSharing(@PathVariable Integer userId) {
        log.info("获取用户[{}]最新位置", userId);
        try {
            LocationSharing locationSharing = locationSharingService.getLatestLocationSharing(userId);
            if (locationSharing != null) {
                return R.success(locationSharing);
            } else {
                return R.error("未找到位置信息");
            }
        } catch (Exception e) {
            log.error("获取位置信息异常", e);
            return R.error("获取位置信息异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户历史位置
     * @param userId 用户ID
     * @param limit 限制数量
     * @return 历史位置列表
     */
    @GetMapping("/location-sharing/history/{userId}")
    public R<List<LocationSharing>> getLocationSharingHistory(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "10") Integer limit) {
        log.info("获取用户[{}]历史位置，限制数量[{}]", userId, limit);
        try {
            List<LocationSharing> locationSharingList = locationSharingService.getLocationSharingHistory(userId, limit);
            return R.success(locationSharingList);
        } catch (Exception e) {
            log.error("获取历史位置异常", e);
            return R.error("获取历史位置异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户与目标的共享位置
     * @param userId 用户ID
     * @param targetId 目标ID
     * @return 共享位置信息
     */
    @GetMapping("/location-sharing/{userId}/{targetId}")
    public R<LocationSharing> getLocationSharingByUserAndTarget(
            @PathVariable Integer userId,
            @PathVariable Integer targetId) {
        log.info("获取用户[{}]与目标[{}]的共享位置", userId, targetId);
        try {
            LocationSharing locationSharing = locationSharingService.getLocationSharingByUserAndTarget(userId, targetId);
            if (locationSharing != null) {
                return R.success(locationSharing);
            } else {
                return R.error("未找到共享位置信息");
            }
        } catch (Exception e) {
            log.error("获取共享位置信息异常", e);
            return R.error("获取共享位置信息异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户的共享对象列表
     * @param userId 用户ID
     * @return 共享对象列表
     */
    @GetMapping("/share-targets/user/{userId}")
    public R<List<ShareTarget>> getShareTargetsByUserId(@PathVariable Integer userId) {
        log.info("获取用户[{}]的共享对象列表", userId);
        try {
            List<ShareTarget> shareTargets = shareTargetService.getShareTargetsByUserId(userId);
            return R.success(shareTargets);
        } catch (Exception e) {
            log.error("获取用户共享对象列表异常", e);
            return R.error("获取用户共享对象列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取共享对象列表
     * @param userId 用户ID
     * @param type 类型（可选）
     * @return 共享对象列表
     */
    @GetMapping("/share-targets/{userId}")
    public R<List<ShareTarget>> getShareTargets(
            @PathVariable Integer userId,
            @RequestParam(required = false) String type) {
        log.info("获取用户[{}]的共享对象列表，类型[{}]", userId, type);
        try {
            List<ShareTarget> shareTargets = shareTargetService.getShareTargetsByUserIdAndType(userId, type);
            return R.success(shareTargets);
        } catch (Exception e) {
            log.error("获取共享对象列表异常", e);
            return R.error("获取共享对象列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 添加共享对象
     * @param shareTarget 共享对象
     * @return 操作结果
     */
    @PostMapping("/share-targets")
    public R<String> addShareTarget(@RequestBody ShareTarget shareTarget) {
        log.info("添加共享对象: {}", shareTarget);
        try {
            boolean result = shareTargetService.addShareTarget(shareTarget);
            if (result) {
                return R.success("添加共享对象成功");
            } else {
                return R.error("添加共享对象失败");
            }
        } catch (Exception e) {
            log.error("添加共享对象异常", e);
            return R.error("添加共享对象异常: " + e.getMessage());
        }
    }
    
    /**
     * 更新共享对象
     * @param shareTarget 共享对象
     * @return 操作结果
     */
    @PutMapping("/share-targets")
    public R<String> updateShareTarget(@RequestBody ShareTarget shareTarget) {
        log.info("更新共享对象: {}", shareTarget);
        try {
            boolean result = shareTargetService.updateShareTarget(shareTarget);
            if (result) {
                return R.success("更新共享对象成功");
            } else {
                return R.error("更新共享对象失败");
            }
        } catch (Exception e) {
            log.error("更新共享对象异常", e);
            return R.error("更新共享对象异常: " + e.getMessage());
        }
    }
    
    /**
     * 删除共享对象
     * @param id 共享对象ID
     * @return 操作结果
     */
    @DeleteMapping("/share-targets/{id}")
    public R<String> deleteShareTarget(@PathVariable Integer id) {
        log.info("删除共享对象: {}", id);
        try {
            boolean result = shareTargetService.deleteShareTarget(id);
            if (result) {
                return R.success("删除共享对象成功");
            } else {
                return R.error("删除共享对象失败");
            }
        } catch (Exception e) {
            log.error("删除共享对象异常", e);
            return R.error("删除共享对象异常: " + e.getMessage());
        }
    }
} 